package mh.demo.im.websocket;

import mh.demo.im.sse.SseController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.IOException;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArraySet;

@Component
@EnableScheduling
public class TimeTask {
    private static final Logger logger = LoggerFactory.getLogger(TimeTask.class);

    private final SseController sseController;

    @Autowired
    public TimeTask(SseController sseController) {
        this.sseController = sseController;
    }

    @Scheduled(cron = "0/3 * * * * ?")
    public void sendMsgTaskForSse() {
        Map<String, SseEmitter> sseMap = sseController.getSseMap();
        sseMap.forEach((id, emitter) -> {
            if (emitter != null) {
                try {
                    emitter.send("随机消息 - " + new Random().nextInt(10000000));
                } catch (Exception e) {
                    logger.error("send message error", e);
                }
            }
        });
    }

    @Scheduled(cron = "0/3 * * * * ?")
    public void sendMsgTaskForWebSocket() {
        CopyOnWriteArraySet<MyWebSocket> webSocketSet = MyWebSocket.getWebSocketSet();
        webSocketSet.forEach(c -> {
            try {
                c.sendMessage("随机消息 - " + new Random().nextInt(10000000));
            } catch (IOException e) {
                logger.error("send message error", e);
            }
        });
    }

}
